<template>
  <div class="login-container">
    <h2>用户登录</h2>
    <form @submit.prevent="handleLogin">
      <!-- 手机号输入 -->
      <div class="form-group">
        <label>手机号</label>
        <input
          v-model="form.phone"
          type="text"
          placeholder="请输入手机号"
          @blur="validatePhone"
        />
        <span class="error" v-if="phoneError">{{ phoneError }}</span>
      </div>

      <!-- 密码输入 -->
      <div class="form-group">
        <label>密码</label>
        <input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
        />
      </div>

      <!-- 图片验证码 -->
      <div class="form-group">
        <label>图片验证码</label>
        <div class="captcha-group">
          <input
            v-model="form.imageCaptcha"
            type="text"
            placeholder="请输入图片验证码"
          />
          <img
            :src="imageCaptchaUrl"
            @click="refreshImageCaptcha"
            alt="点击刷新验证码"
            class="captcha-image"
          />
        </div>
      </div>

      <!-- 短信验证码 -->
      <div class="form-group">
        <label>短信验证码</label>
        <div class="sms-group">
          <input
            v-model="form.smsCaptcha"
            type="text"
            placeholder="请输入短信验证码"
          />
          <button
            type="button"
            @click="sendSmsCaptcha"
            :disabled="isSendingSms"
            class="sms-btn"
          >
            {{ isSendingSms ? `${smsCountdown}秒后重试` : '获取验证码' }}
          </button>
        </div>
      </div>

      <!-- 登录按钮 -->
      <button type="submit" class="login-btn">登录</button>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const api='http://127.0.0.1:8000'
// 表单数据
const form = reactive({
  phone: '',
  password: '',
  imageCaptcha: '',
  smsCaptcha: ''
})

// 图片验证码URL
const imageCaptchaUrl = ref('')
// 短信验证码发送状态
const isSendingSms = ref(false)
const smsCountdown = ref(60)
// 手机号错误提示
const phoneError = ref('')

// 初始化图片验证码
const refreshImageCaptcha = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:8000/login/image/', {
      responseType: 'blob'
    })
    imageCaptchaUrl.value = URL.createObjectURL(response.data)
  } catch (error) {
    console.error('获取图片验证码失败:', error)
    alert('获取验证码失败，请重试')
  }
}

// 验证手机号格式
const validatePhone = () => {
  const reg = /^1[3-9]\d{9}$/
  if (!reg.test(form.phone)) {
    phoneError.value = '手机号格式不正确'
  } else {
    phoneError.value = ''
  }
}

// 发送短信验证码
const sendSmsCaptcha = async () => {
  if (!form.phone) {
    alert('请输入手机号')
    return
  }

  if (phoneError.value) {
    alert('请先修正手机号格式')
    return
  }

  if (!form.imageCaptcha) {
    alert('请输入图片验证码')
    return
  }

  try {
    // 先验证图片验证码
    await axios.post('http://127.0.0.1:8000/login/image/', {
      captcha: form.imageCaptcha
    })

    // 发送短信验证码
    isSendingSms.value = true
    await axios.post('http://127.0.0.1:8000/login/code/', {
      phone: form.phone
    })

    // 开始倒计时
    const timer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(timer)
        isSendingSms.value = false
        smsCountdown.value = 60
      }
    }, 1000)

    alert('短信验证码发送成功')
  } catch (error) {
    console.error('发送短信验证码失败:', error)
    alert(error.response?.data?.msg || '发送验证码失败')
    isSendingSms.value = false
    // 刷新图片验证码
    refreshImageCaptcha()
    form.imageCaptcha = ''
  }
}

// 处理登录
const handleLogin = async () => {
  if (!form.phone || !form.password || !form.smsCaptcha) {
    alert('请填写完整信息')
    return
  }

  try {
    const response = await axios.post('http://127.0.0.1:8000/login/login/', {
      phone: form.phone,
      password: form.password,
      code: form.smsCaptcha
    })

    // 存储token并跳转
    localStorage.setItem('token', response.data.token)
    router.push('/')
  } catch (error) {
    console.error('登录失败:', error)
    alert(error.response?.data?.message || '登录失败')
    // 刷新图片验证码
    refreshImageCaptcha()
    form.imageCaptcha = ''
    form.smsCaptcha = ''
  }
}

// 组件挂载时获取图片验证码
onMounted(() => {
  refreshImageCaptcha()
})
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
}

input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.error {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.captcha-group {
  display: flex;
  gap: 10px;
}

.captcha-image {
  width: 120px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.sms-group {
  display: flex;
  gap: 10px;
}

.sms-btn {
  white-space: nowrap;
  padding: 0 15px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.sms-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
}

.login-btn:hover {
  background: #40a9ff;
}
</style>